﻿using System.Collections.Generic;

namespace HCore
{
    public class RecordData : IReadWrite
    {
        public Dictionary<int, List<TurnData>> turnMap => _turnMap;
        public Dictionary<int, string> serverProxies => _serverProxies;

        private readonly Dictionary<int, List<TurnData>> _turnMap;
        private readonly Dictionary<int, string> _serverProxies;

        public RecordData(Dictionary<int, List<TurnData>> tm, Dictionary<int, string> sp)
        {
            Debug.Assert(tm != null);
            Debug.Assert(sp != null);
            _turnMap = tm;
            _serverProxies = sp;
        }

        public RecordData(InputMemoryBitStream input)
        {
            _turnMap = new Dictionary<int, List<TurnData>>();
            _serverProxies = new Dictionary<int, string>();
            Read(input);
        }

        public void Write(OutputMemeryBitStream output)
        {
            int count = _turnMap.Count;
            output.WriteInt(count);
            foreach (var kv in _turnMap)
            {
                int playerId = kv.Key;
                List<TurnData> turnDatas = kv.Value;
                int turnDatasCount = turnDatas.Count;
                output.WriteInt(playerId);
                output.WriteInt(turnDatasCount);
                foreach (var turnData in turnDatas)
                {
                    turnData.Write(output);
                }
            }

            count = _serverProxies.Count;
            output.WriteInt(count);
            foreach (var kv in _serverProxies)
            {
                int playerId = kv.Key;
                string name = kv.Value;
                output.WriteInt(playerId);
                output.WriteString(name);
            }
        }

        public void Read(InputMemoryBitStream input)
        {
            _turnMap.Clear();
            _serverProxies.Clear();
            int count = input.ReadInt();
            for (int i = 0; i < count; i++)
            {
                int playerId = input.ReadInt();
                int turnDatasCount = input.ReadInt();
                List<TurnData> turnDatas = new List<TurnData>();
                for (int j = 0; j < turnDatasCount; j++)
                {
                    TurnData turnData = new TurnData();
                    turnData.Read(input);
                    turnDatas.Add(turnData);
                }

                _turnMap.Add(playerId, turnDatas);
            }

            count = input.ReadInt();
            for (int i = 0; i < count; i++)
            {
                int playerId = input.ReadInt();
                string name = input.ReadString();
                _serverProxies.Add(playerId, name);
            }
        }
    }
}